package com.hema.auction.fragment;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.activity.GoodsDetailsActivity;
import com.hema.auction.adapter.GoodsAdapter;
import com.hema.auction.adapter.GoodsTabAdapter;
import com.hema.auction.base.BaseFragment;
import com.hema.auction.bean.GoodTypeInfo;
import com.hema.auction.bean.GoodsInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.widget.view.MyLoadMoreView;
import com.hema.auction.widget.view.RefreshRecyclerView;
import com.hema.auction.widget.view.TitleView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;


/**
 * author by john
 * 商品分类
 */
public class GoodsFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerviewTab;
    private GoodsTabAdapter tabAdapter;
    @BindView(R.id.refresh_recycler_view)
    RefreshRecyclerView refreshRecyclerView;
    @BindView(R.id.ll_empty)
    LinearLayout llEmpty;
    private GoodsAdapter goodsAdapter;
    private List<GoodsInfo> goodsInfos = new ArrayList<>();
    private List<GoodTypeInfo> goodTypeInfos = new ArrayList<>();
    private String id = "0";
    private int collectIndex;

    @Override
    protected int getLayout() {
        return R.layout.fragment_goods;
    }

    @Override
    protected void init() {
        super.init();
        ButterKnife.bind(this, view);
        initTab();
        initContent();
    }

    private void initTab() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerviewTab.setLayoutManager(layoutManager);
        tabAdapter = new GoodsTabAdapter(goodTypeInfos);
        recyclerviewTab.setAdapter(tabAdapter);
        recyclerviewTab.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .colorResId(R.color.colorDivider).showLastDivider()
                .size(2).build());
        tabAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                tabAdapter.selected(position);
                tabAdapter.notifyDataSetChanged();
                id = tabAdapter.getData().get(position).getId();
                refreshRecyclerView.setRefresh(true);
            }
        });
        HttpManager.getInstance(getActivity()).getAllTypes(this);
    }

    private void initContent() {
        refreshRecyclerView.setVerLayoutManager();
        goodsAdapter = new GoodsAdapter(goodsInfos);
        goodsAdapter.setLoadMoreView(new MyLoadMoreView());
        refreshRecyclerView.setAdapter(goodsAdapter);
        refreshRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .colorResId(R.color.colorDivider).marginProvider(goodsAdapter)
                .size(2).build());
        refreshRecyclerView.setOnRefreshListener(this);
        goodsAdapter.setOnLoadMoreListener(this, refreshRecyclerView.getRecyclerView());
        goodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putParcelable(Constant.EXTRA_GOOD_INFO, (GoodsInfo) adapter.getData().get(position));
                intentTo(GoodsDetailsActivity.class, bundle);
            }
        });
        goodsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (isLogin) {
                    collectIndex = position;
                    showProgressDialog();
                    if (goodsAdapter.getData().get(position).getIsCollected() == 0) {
                        HttpManager.getInstance(getActivity()).collectGood(goodsAdapter.getData().get(position).getId(), GoodsFragment.this);
                    } else {
                        HttpManager.getInstance(getActivity()).delCollection(goodsAdapter.getData().get(position).getId(), GoodsFragment.this);
                    }
                } else {
                    goLogin();
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
//        if (goodTypeInfos.isEmpty())
//            HttpManager.getInstance(getActivity()).getAllTypes(this);
//        else {
            pageIndex = 1;
            HttpManager.getInstance(getActivity()).getGoodsByCategory(id, pageIndex, pageSize, this);
//        }
    }

    @Override
    protected void onLoadMore() {
        super.onLoadMore();
        pageIndex++;
        HttpManager.getInstance(getActivity()).getGoodsByCategory(id, pageIndex, pageSize, this);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_ALL_TYPES:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<GoodTypeInfo> goodTypeInfos = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<GoodTypeInfo>>() {
                        }.getType());
                        GoodTypeInfo info = new GoodTypeInfo();
                        info.setId("0");
                        info.setName("全部");
                        goodTypeInfos.add(0, info);
                        tabAdapter.setNewData(goodTypeInfos);
                        refreshRecyclerView.setRefresh(true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_GET_GOODS_BY_CATEGORY:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<GoodsInfo> goodsInfos = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<GoodsInfo>>() {
                        }.getType());
                        if (pageIndex == 1) {
                            goodsAdapter.setNewData(goodsInfos);
                            if (goodsInfos.size() < pageSize) {
                                goodsAdapter.setEnableLoadMore(false);
                            } else {
                                goodsAdapter.setEnableLoadMore(true);
                            }
                        } else {
                            goodsAdapter.addData(goodsInfos);
                            goodsAdapter.loadMoreComplete();
                            if (goodsInfos.size() < pageSize) {
                                goodsAdapter.loadMoreEnd();
                            }
                        }
                        if (goodsAdapter.getItemCount() > 0) {
                            llEmpty.setVisibility(View.GONE);
                        } else {
                            llEmpty.setVisibility(View.VISIBLE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_COLLECT_GOOD:
                try {
                    if (result.getInt("errcode") == 0) {
                        goodsAdapter.getData().get(collectIndex).setIsCollected(1);
                        goodsAdapter.notifyItemChanged(collectIndex);
                    }
//                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_DEL_COLLECT:
                try {
                    if (result.getInt("errcode") == 0) {
                        goodsAdapter.getData().get(collectIndex).setIsCollected(0);
                        goodsAdapter.notifyDataSetChanged();
                    }
//                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        refreshRecyclerView.setRefresh(false);
    }

}
